import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter TabBarView 示例',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: const TabViewHomePage(),
      routes: {
        '/tab1': (context) => const TabViewRoute1(),
        '/tab2': (context) => const TabViewRoute2(),
      },
    );
  }
}

class TabViewHomePage extends StatelessWidget {
  const TabViewHomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('TabBarView 演示')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: () {
                Navigator.pushNamed(context, '/tab1');
              },
              child: const Text('手动管理 TabController'),
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                Navigator.pushNamed(context, '/tab2');
              },
              child: const Text('使用 DefaultTabController'),
            ),
          ],
        ),
      ),
    );
  }
}

// 方式一：手动创建和管理 TabController
class TabViewRoute1 extends StatefulWidget {
  const TabViewRoute1({super.key});

  @override
  _TabViewRoute1State createState() => _TabViewRoute1State();
}

class _TabViewRoute1State extends State<TabViewRoute1>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  final List<String> tabs = ["新闻", "历史", "图片", "视频"];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: tabs.length, vsync: this);
    _tabController.addListener(() {
      // 可以在此监听标签切换事件
      if (_tabController.indexIsChanging) {
        print('当前选中标签索引: ${_tabController.index}');
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("App Name"),
        bottom: TabBar(
          controller: _tabController,
          isScrollable: true, // 允许标签滚动
          indicatorColor: Colors.white, // 指示器颜色
          indicatorWeight: 3.0, // 指示器高度
          labelColor: Colors.white, // 选中标签文本颜色
          unselectedLabelColor: Colors.white70, // 未选中标签文本颜色
          tabs: tabs.map((e) => Tab(text: e)).toList(),
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        // 使用KeepAliveWrapper实现页面缓存
        children:
            tabs.map((tabName) {
              return KeepAliveWrapper(
                child: Container(
                  alignment: Alignment.center,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        tabName,
                        textScaleFactor: 3,
                        style: const TextStyle(fontWeight: FontWeight.bold),
                      ),
                      const SizedBox(height: 20),
                      Text(
                        '$tabName 内容区域',
                        style: const TextStyle(fontSize: 20),
                      ),
                    ],
                  ),
                ),
              );
            }).toList(),
      ),
    );
  }

  @override
  void dispose() {
    _tabController.dispose(); // 释放资源
    super.dispose();
  }
}

// 方式二：使用DefaultTabController简化实现
class TabViewRoute2 extends StatelessWidget {
  const TabViewRoute2({super.key});

  @override
  Widget build(BuildContext context) {
    final List<String> tabs = ["新闻", "历史", "图片", "设置"];
    return DefaultTabController(
      length: tabs.length,
      child: Scaffold(
        appBar: AppBar(
          title: const Text("App Name"),
          bottom: TabBar(
            // 自定义指示器样式
            indicator: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(10),
            ),
            indicatorPadding: const EdgeInsets.symmetric(horizontal: 10),
            labelStyle: const TextStyle(fontWeight: FontWeight.bold),
            tabs:
                tabs.map((e) {
                  return Tab(
                    text: e,
                    // 为不同标签添加图标
                    icon:
                        e == "新闻"
                            ? const Icon(Icons.newspaper)
                            : e == "历史"
                            ? const Icon(Icons.history)
                            : e == "图片"
                            ? const Icon(Icons.image)
                            : const Icon(Icons.settings),
                  );
                }).toList(),
          ),
        ),
        body: TabBarView(
          // 为每个标签页添加不同的内容
          children:
              tabs.map((tabName) {
                return Padding(
                  padding: const EdgeInsets.all(20.0),
                  child: Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        const Icon(Icons.info, size: 60, color: Colors.blue),
                        const SizedBox(height: 20),
                        Text(
                          '$tabName 页面',
                          style: const TextStyle(
                            fontSize: 28,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        const SizedBox(height: 10),
                        Text(
                          '这是$tabName的具体内容区域，可以在此添加复杂的UI组件',
                          textAlign: TextAlign.center,
                          style: const TextStyle(
                            fontSize: 16,
                            color: Colors.grey,
                          ),
                        ),
                      ],
                    ),
                  ),
                );
              }).toList(),
        ),
      ),
    );
  }
}

// 页面缓存包装器，需要在pubspec.yaml中添加flutter_keep_alive依赖
class KeepAliveWrapper extends StatefulWidget {
  final Widget child;

  const KeepAliveWrapper({super.key, required this.child});

  @override
  _KeepAliveWrapperState createState() => _KeepAliveWrapperState();
}

class _KeepAliveWrapperState extends State<KeepAliveWrapper>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true; // 保持页面活动状态

  @override
  Widget build(BuildContext context) {
    super.build(context); // 必须调用
    return widget.child;
  }
}
